package com.appbee.cm.client.modular.ui;

import javax.inject.Inject;

import com.appbee.cm.client.modular.presenter.ModulSelectionBoxPresenter;
import com.appbee.cm.client.modular.presenter.ModulTreeViewModel;
import com.appbee.core.client.modular.IModul;
import com.google.gwt.user.cellview.client.CellTree;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.UIObject;
import com.google.gwt.view.client.SelectionChangeEvent;
import com.google.gwt.view.client.SingleSelectionModel;

public class ModulSelectPopup extends Composite implements
		ModulSelectionBoxPresenter.SelectView
{
	private final PopupPanel popupPanel = new PopupPanel();
	private final CellTree tree;
	private ModulSelectionBoxPresenter presenter;
	private final SingleSelectionModel<IModul> selectionModel;

	@Inject
	public ModulSelectPopup(final ModulTreeViewModel modulTreeViewModel)
	{
		this.selectionModel = modulTreeViewModel.getSelectionModel();
		tree = new CellTree(modulTreeViewModel, null);
		initWidget(tree);
		popupPanel.setWidget(this);
		popupPanel.setAutoHideEnabled(true);
		selectionModel
				.addSelectionChangeHandler(new SelectionChangeEvent.Handler()
				{

					@Override
					public void onSelectionChange(SelectionChangeEvent event)
					{
						presenter.onModulSelected(selectionModel
								.getSelectedObject());
					}
				});
	}

	@Override
	public void setPresenter(ModulSelectionBoxPresenter presenter)
	{
		this.presenter = presenter;
	}

	@Override
	public void setSelectedValue(IModul value)
	{
		if (value == null)
		{
			IModul selectedObject = selectionModel.getSelectedObject();
			if (selectedObject != null)
				selectionModel.setSelected(selectedObject, false);
		}
		else
			selectionModel.setSelected(value, true);
	}

	@Override
	public void show(Object source)
	{
		popupPanel.showRelativeTo((UIObject) source);
	}

	@Override
	public void hide()
	{
		popupPanel.hide();
	}

}
